import sys
import turtle

'''
turtle.pensize(5)
turtle.pencolor('green')

turtle.right(-30)
turtle.forward(60)
turtle.right(60)
turtle.forward(60)
turtle.right(95)
turtle.forward(180)
turtle.right(110)
turtle.forward(180)
turtle.right(90)
turtle.forward(60)
turtle.right(70)
turtle.forward(60)

turtle.mainloop()
'''
'''
a = 100
b = 12.345
c = 1 + 5j
d = 'hello, world'
e = True
print(type(a))    # <class 'int'>
print(type(b))    # <class 'float'>
print(type(c))    # <class 'complex'>
print(type(d))    # <class 'str'>
print(type(e))    # <class 'bool'>

a = int(input('a = '))
b = int(input('b = '))
print('%d + %d = %d' % (a, b, a + b))
print('%d - %d = %d' % (a, b, a - b))
print('%d * %d = %d' % (a, b, a * b))
print('%d / %d = %f' % (a, b, a / b))
print('%d // %d = %d' % (a, b, a // b))
print('%d %% %d = %d' % (a, b, a % b))
print('%d ** %d = %d' % (a, b, a ** b))

# 华氏度转摄氏温度
f = float(input('请输入摄氏度：'))
c = (f - 32) / 1.8
print('%.1f华氏温度= %.1f摄氏度' % (f, c))


# 输入圆的半径计算计算周长和面积
r = int(input("please input the circle's radius:"))
P = 3.14
# circumference
c = 2 * P * r
s = P * r * r
print('circumference:%.2f' % c)
print(f"area:{s:.2f}")
#The code above's first 'f' means the whole print's type



# 输入年份判断是不是闰年
year = int(input('please input the year:'))
result = year % 4 == 0 and year % 100 != 0 \
         or year % 400 == 0
# The '\'means if the code is too long you can cut it in two lines for read conviniently
print(result)


# 英制单位英寸和公制单位厘米互换
value = float(input("please input the length:"))
unit = input("please input the unit:")

if unit == 'in' or unit == '英寸':
    print("%f in=%f cm" % (value, value * 2.54))
elif unit == 'cm' or unit == '厘米':
    print("%f cm=%f in" % (value, value / 2.54))
else:
    print("The unit you inputted is wrong!")

# 百分制成绩转换为等级制成绩。
# 要求：如果输入的成绩在90分以上（含90分）输出A；80分-90分（不含90分）输出B；70分-80分（不含80分）输出C；60分-70分（不含70分）输出D；60分以下输出E。
score = float(input("Please input the score:"))
if score >= 90:
    print('A')
elif score >= 80:
    print('B')
elif score >= 70:
    print('C')
elif score >= 60:
    print('D')
else:
    print('E')

# 输入三条边长，如果能构成三角形就计算周长和面积。
a = float(input("Please enter the first side length:"))
b = float(input("Please enter the second side length:"))
c = float(input("Please enter the third side length:"))
if a + b > c and a + c > b and b + c > a:
    print("It can form a triangle")
    circumference = a + b + c
    p=circumference/2
    area = (p * (p - a) * (p - b) * (p - c) ) ** 0.5
    print("circumference:%f" % circumference)
    print("area:%f" % area)
else:
    print("It can't form a triangle")

from math import sqrt

num = int(input("Please enter the number:"))
end = int(sqrt(num))
is_prime=True
for x in range(2,end+1):
    if num %x==0:
        is_prime=False
        break
if is_prime==True and num !=1:
    print("%d is a prime"%num)
else:
    print("%d is not a prime"%num)

x = int(input('x = '))
y = int(input('y = '))
if x > y:
    x, y = y, x
    # This code means exchange x and y
for factor in range(x, 0, -1):
    if x % factor == 0 and y % factor == 0:
        print("%d and %d's Greatest common divisor is: %d" % (x, y, factor))
        print("%d and %d's least common multiple is: %d" % (x, y, x * y // factor))
        break


row = int(input("Please enter the rows:"))
for x in range(1, row + 1):
    for y in range(1, x + 1):
        print('*', end=' ')
    print('\n')

for x in range(1, row + 1):
    for y in range(1, row - x + 1):
        print(' ', end=' ')
    for z in range(1, x + 1):
        print('*', end=' ')
    print('\n')

for x in range(1, row + 1):
    for y in range(1, row - x + 1):
        print(' ', end=' ')
    for z in range(1, (2 * x) - 1 + 1):
        print('*', end=' ')
    print('\n')

#寻找水仙花数。
for num in range(100,1000):
    a=num//100
    b=num//10%10
    c=num%10
    if a**3+b**3+c**3==num:
        #print("%d"%num,end=' ')

# 正整数的反转
num = int(input("Please enter a Positive integer:"))
reserve_num = 0;
while num > 0:
    reserve_num = reserve_num * 10 + num % 10
    num = num // 10
print(reserve_num)


#百钱百鸡问题
for a in range(0,20):
    for b in range(0,33):
        c=(100-a-b)
        if c*(1/3)+a*5+b*3==100:
            print('公鸡: %d只, 母鸡: %d只, 小鸡: %d只' % (a, b, c))



for x in range(0, 20):
    for y in range(0, 33):
        z = 100 - x - y
        if 5 * x + 3 * y + z / 3 == 100:
            print('公鸡: %d只, 母鸡: %d只, 小鸡: %d只' % (x, y, z))


# CRAPS赌博游戏。
from random import randint

money = 1000
while money > 0:
    print("Your estate:%d" % money)
    # Make a bet
    while True:
        debt = int(input("Enter your debt:"))
        if 0 < debt <= money:
            break
        else:
            print("You don't have enough money!")
    # Gamble start
    GameJudge = False
    First = randint(1, 6) + randint(1, 6)
    print("The First result is:%d" % First)
    if First == 7 or First == 11:
        print("Player win!")
        GameJudge = False

    elif First == 2 or First == 3 or First == 12:
        print("Banker win!")
        GameJudge = True
    else:
        while True:
            Go = randint(1, 6) + randint(1, 6)
            print("Try again:%d" % Go)
            if Go == 7:
                print("Banker win!")
                GameJudge = True
                break
            elif Go == First:
                print("Player win!")
                GameJudge = False
                break
    # Settle account
    if GameJudge == False:
        money += debt * 2
    else:
        money -= debt
print("Your balance is empty!")

# 生成斐波那契数列的前20个数

for num in range(1, 21):
    if num < 3:
        a = b = c= 1
        print(c)
    else:
        c=a+b
        a=b
        b=c
        print(c)

a=0
b=1
for _ in range(20):
    a,b=b,a+b
    print(a,end=' ')

# 找出10000以内的完美数
for num in range(1, 10001):
    max = num // 2
    for i in range(1, max + 1):
        if num % i == 0:
            sum += i
    if num == sum:
        print(num, end=' ')

import math

for num in range(2, 10000):
    result = 0
    for factor in range(1, int(math.sqrt(num)) + 1):
        if num % factor == 0:
            result += factor
            if factor > 1 and num // factor != factor:
                result += num // factor
    if result == num:
        print(num)

for num in range(1, 10001):
    max = num // 2
    sum = 0
    for i in range(1, max + 1):
        if num % i == 0:
            sum += i
    if num == sum:
        print(num, end=' ')
from random import randint

from random import randint

def roll_dice(n=2):
    """摇色子"""
    total = 0
    for _ in range(n):
        total += randint(1, 6)
    return total


def add(a=0, b=0, c=0):
    """三个数相加"""
    return a + b + c


# 如果没有指定参数那么使用默认值摇两颗色子
print(roll_dice())
# 摇三颗色子
print(roll_dice(3))
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
# 传递参数时可以不按照设定的顺序进行传递
print(add(c=50, a=100, b=200))



# 在参数名前面的*表示args是一个可变参数
def add(*args):
    total = 0
    for val in args:
        total += val
    return total


# 在调用add函数时可以传入0个或多个参数
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9))


#输出100以内所有的素数

for a in range(2,101):
    judge = 1
    num =a//2
    for b in range(2,num+1):
        if a%b==0:
            judge=0
            break
    if judge==1:
        print(a,end=' ')


import module

x = int(input("Please enter the first number:"))
y = int(input("Please enter the second number:"))
mcf = module.mcf(x, y)
lcm = module.lcm(x, y)
print("The maximum common factor is:%d" % mcf)
print("The least common mutiple is:%d" % lcm)


import module as md
num =int(input("Please enter the number:"))
print(md.is_palindrome(num))


from module import is_prime
num =int(input("Please enter the number:"))
print(is_prime(num))


s1 = '\'hello, world!\''
s2 = '\n\\hello, world!\\\n'
print(s1, s2, end='')


s1 = '\141\142\143\x61\x62\x63'
s2 = '\u9a86\u660a'
print(s1, s2)

s1 = r'\'hello, world!\''
s2 = r'\n\\hello, world!\\\n'
print(s1, s2, end='')


str1 = 'hello, world!'
print(str1.center(20, '*'))
print(str1.rjust(20, '*'))
print(str1.ljust(20,'*'))


str2 ='  jackfrued@126.com '
print(str2)
print(str2.strip())


a, b = 5, 10
print('{0}*{2}={1}' .format(a, b, a * b))
print(f'{a}*{b}={a*b}')


print('\n'.join([''.join([('IloveU'[(x-y)%len('IloveU')]\
                               if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')\
                          for x in range(-30,30)])for y in range(15,-15,-1)]))

list = [1, 2, 3, 4, 5]
list.append(100)
list.insert(2, 100)

list += [1, 2]
if 3 in list:
    list.remove(3)
if 1234 in list:
    list.remove(1234)
list.pop(0)
list.pop(len(list)-1)
list.pop(2)

list.clear()
print(list)


list1 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']
list2 = sorted(list1)
list3 = sorted(list1, reverse=True)
list4 = sorted(list1, key=len)

print(list2)
print(list3)
print(list4)
list1.sort(reverse=True)
print(list1)


list1 = [a for a in range(1, 10)]
list2 = [a + b for a in 'abbcdef' for b in '123456' ]

print(list1)
print(list2)


a = [x ** 2 for x in range(1, 100)]
print(sys.getsizeof(a))
print(a)
b = (x ** 2 for x in range(1, 100))
print(sys.getsizeof(a))
print(a)
for val in a:
    print(val)
for val in b:
    print(val)



def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
        yield a
def main():
    for val in fib(20):
        print(val)


if __name__ == '__main__':
    main()


t = ('linjianhua', '2002_11_10', 'student')
print(t)
print(t[0])
print(t[2])
for val in t:
    print(val)
# redefine tuple
t = ('zhangsan', '18', 'bangkok')
print(t)
# tuple to list
list = list(t)
print(list)
# modify list elements
list[0]='FeiFan Liu'
print(list)

# list to tuple
list1=['zhangsan', '18', 'bangkok']
tuple1 =tuple(list1)
print(tuple1)

# create a set
set1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1)
# create a set using constructor syntax
set2 = set(range(1, 10))
set3 = set((2, 1, 1, 2, 1, 3, 1, 4, 3))
print(set2, set3)
# create a set using comprehension syntax
set4 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0}
print(set4)

# add elements
set1.add(10)
print(set1)
# update elements
set2.update([10, 11, 12, 13])
print(set2)
# delete elements
set2.discard(13)
set2.remove(12)
if 11 in set2:
    set2.remove(11)
print(set2)
set2.pop()
print(set2)
# pop function


set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# intersection union difference symmetric_difference
# intersection
print(set1 & set2)
print(set1.intersection(set2))
# union
print(set1 | set2)
print(set1.union(set2))
# difference
print(set1 - set2)
print(set1.difference(set2))
# symmetric_difference
print(set1 ^ set2)
print(set1.symmetric_difference(set2))

# create dictionary

score = {'zhangsan': 20, 'lisi': 30, 'wangwu': 40}
print(score)
# dictionary literal syntax
items1 = dict(zhangsan=10, lisi=30, wangwu=40)
print(items1)
# dictionary constructor syntax
# items2 = dict(zip(['zhangsan', 'lisi', 'wangwu'],'123'))
items2 = dict(zip(['zhangsan', 'lisi', 'wangwu'], [12, 13, 14, 15]))
print(items2)

# zip function
items3 = {num: num ** 3 for num in range(1, 10)}
items4 = {'123': num ** 3 for num in range(1, 4)}
print(items3)
print(items4)
# comprehension syntax

scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
for key in scores:
    print(f'{key}:{scores[key]}')
scores['骆昊']=101
scores['白元芳']=99
scores.update(zhangsan=90,lisi=100,wangwu=60)
print(scores)
if 'zhangsan' in scores:
    scores['zhangsan']=100
print(scores)
print(scores.get('zhangsan'))
print(scores.get('mazi'))
print(scores.get('mazi',100))
print(scores)
print(scores.popitem())
print(scores.popitem())
print(scores.pop('zhangsan'))
print(scores)

import os
import time

def main():
    content = 'welcome to the highest city of the world:Li Tang......'
    while True:
        # clean the screen
        #os.system('cls')
        #os.system('clear')
        print(content)
        # sleep 200 milliseconds
        time.sleep(0.2)
        # print the content
        content = content[1:] + content[0]

if __name__ == '__main__':
    main()

# 导入随机包
import random


def generate_code(code_len=4):
    # 生成随即选项
    all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    # 数值初始化
    length = len(all_chars) - 1
    code = ''
    # 循环四次生成随机代码
    for _ in range(code_len):
        index = random.randint(0, length)
        code += all_chars[index]
    print(code)

def get_suffix(filemane, has_dot=False):
if __name__ == '__main__':

s1 = r'\n\n\n1234566'
print(s1)

s1 = r'\'\'\'\'\\\t\r\e\w'
s2 = r'\n\\\\\\\\\\'
print(s1, s2, end='123')

str = 'abc12345'
print(str[:5])
print(str[2:4])
print(str[::-1])
print(str[::3])
print(str[::-3])
print(len(str))

str = 'abcde'
print(str.center(50, '*'))
print(str.rjust(50, '-'))
print(str.isdigit())
print(str.isalpha())
print(str.isalnum())
str1 = '   155611@qq.com    '
print(str1.strip())
print(str1)

a, b = 5, 10
print('%d * %d = %d' % (a, b, (a * b)))
print('{0} * {1} = {2}'.format(a, b, (a * b)))
print(f'{a} * {b} = {a*b}')


list1 = [1, 2, 3, 4, 5]
for i in range(len(list1)):
    print(list1[i])
for x, y in enumerate(list1):
    print(x, y)

list1 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']
list2 = sorted(list1)
# sorted函数返回列表排序后的拷贝不会修改传入的列表
# 函数的设计就应该像sorted函数一样尽可能不产生副作用
list3 = sorted(list1, reverse=True)
# 通过key关键字参数指定根据字符串长度进行排序而不是默认的字母表顺序
list4 = sorted(list1, key=len)
print(list1)
print(list2)
print(list3)
print(list4)
 
# f = [x for x in range(1, 20)]
# print(f)
f = [x + str(y) for x in 'ABCDE' for y in range(1, 5)]
print(f)
f = [x ** 2 for x in range(1, 1000)]
print(f)
print(sys.getsizeof(f))
f = (x ** 2 for x in range(1, 1000))
print(sys.getsizeof(f))
print(f)
for val in f:
    print(val)



def fib(n):
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
        yield a


def main():
    for val in fib(20):
        print(val)
if __name__ == '__main__':
    main()
print(1)

set2 = set(range(1, 10))
set3 = set((1, 2, 3, 3, 2, 1))
print(set2, set3)
set4 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0}
print(set4)


set = {1, 2, 3, 4}
print(set)
set.add(5)
print(set)
set.discard(4)
print(set)
set.update([11, 12])
print(set)
print(set.pop())
print(set)
items1 = dict(one=1, two=2, three=3, four=4)
# 通过zip函数将两个序列压成字典
items2 = dict(zip(['a', 'b', 'c'], '123'))
# 创建字典的推导式语法
items3 = {num: num ** 2 for num in range(1, 10)}
print(items1, items2, items3)

for key in items1:
    print(f'{key} : {items1[key]}')
print(items1.get('five'))
print(items1.get('five', 60))
print(items1)
print(items1.popitem())
print(items1)
print(items1.pop('five'))
print(items1)

import os
import time


def main():
    content = '>>>>>>>欢迎来到地平线生活<<<<<<<'
    while True:
        # 清理屏幕上的内容
        os.system('cls')
        print(content)
        # 时间暂停0.2秒
        time.sleep(0.2)
        # 更新打印内容
        content = content[1:] + content[0]

import random

def generate_code(code_len = 4):
    All_code='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    code = ''
    Tlen = len(All_code)
    for a in range(code_len):
        i =random.randint(0,Tlen-1)
        code +=All_code[i]
    return code
def main():
    code = generate_code()
    print(code)
    


#练习3：设计一个函数返回给定文件名的后缀名。
def get_suffix(filename):
    pos = filename.rfind('.')
    if pos >= 0:
        last = len(filename)
        index = pos + 1
        return filename[index:last]
    else:
        return ''
def main():
    print(get_suffix('fozahrizon'))



# 设计一个函数返回传入的列表中最大和第二大的元素的值
def max2(lsit):
    m1, m2 = (lsit[0], lsit[1]) if lsit[0] > lsit[1] else (lsit[1], lsit[0])
    for index in range(2, len(lsit)):
        if lsit[index] > m1:
            m2 = m1
            m1 = lsit[index]
        elif m2 < lsit[index]:
            m2 = lsit[index]
    return m1, m2


def main():
    list = [9, 6, 8, 6, 1, 2, 3, 7]
    max = max2(list)
    print(max)



# 计算指定的年月日是这一年的第几天。
def is_leapyear(year):
    return year % 4 & year % 100 != 0 or year % 400 == 0


def which_day(year, month, date):
    days_of_months = [
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    ][is_leapyear(year)]
    total = 0
    for index in range(month - 1):
        total += days_of_months[index]
    return total + date


def main():
    print(which_day(2024, 3, 16))


if __name__ == '__main__':
    main()

print('您好吃了么？' + 'zhangsan')
great = '您好吃了么？'
print(great + 'lisi')
'''

# import math
#
# a = -1
# b = -2
# c = 3
# print((-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a))
# print((-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a))

# shopping_list = ['keyboard', 'keycap']
# shopping_list.append('chair')
# print(shopping_list)

# contacts = {'zhangsan': '1716829374',
#             'lisi': '28723974',
#             'wangwu': '3892794789'}
# contacts['wangmazi'] = '490382909'
# name = input("PLease input your contact name:")
# if name in contacts:
#     print('The contact number is:' + contacts[name])
#     print('The contacts has :' + str(4) + 'persons')
# else:
#     print('Sorry,we can\'t find this person in the contacts!')

# tempreture_dict = {'111':35 ,'123':36, '145':39, '178':39}
# for staff_id,tempreture_num in tempreture_dict.items():
#     if tempreture_num > 38:
#         #print(staff_id +':' +str(tempreture_num))
#        print(staff_id + ':'+str(tempreture_dict[staff_id]))

# print('Welcome to use the calculator:')
# sum = 0
# i = 0
# key = '0'
# print('Please input the numbers:')
# while key != 'q':
#     sum += int(key)
#     i += 1;
#     key = input()
# print("The average is:" + str(sum / i))

# class CuteCat:
#     def __init__(self):
#         self.name = "Lambton"
# cat1 = CuteCat()
# print(cat1.name)

# class CuteCat:
#     def __init__(self, cat_name, cat_age, cat_color):
#         self.name = cat_name
#         self.age = cat_age
#         self.color = cat_color
#
#
# cat1 = CuteCat('huahua', 5, 'orange')
# cat2 = CuteCat('qiuqiu', 6, 'black')
# print(f"No.1 cat's name is {cat1.name} age is {cat1.age} color is {cat1.color}")
# print(f"No.1 cat's name is {cat2.name} age is {cat2.age} color is {cat2.color}")


# class Student:
#     def __init__(self, Stu_name, Stu_id, Stu_Chinese, Stu_Math, Stu_English):
#         self.name = Stu_name
#         self.ID = Stu_id
#         self.Chinese = Stu_Chinese
#         self.Math = Stu_Math
#         self.English = Stu_English
#
#     # def change(self, subject):
#     #     score = input('Please input the score you want to change:')
#     #     subject = score
#
#
#     def Score_Setting(self):
#         change = input('Please input the subject you want to change:')
#         if change == 'Chinese':
#             score = input('Please input the score you want to change:')
#             self.Chinese = score
#         elif change == 'Math':
#             score = input('Please input the score you want to change:')
#             self.Math = score
#         elif change == 'English':
#             score = input('Please input the score you want to change:')
#             self.English = score
#         # if change == 'Chinese':
#         #     change(self.Chinese)
#         # elif change == 'Math':
#         #     change(self.Math)
#         # elif change == 'English':
#         #     change(self.English)
#
#     def Print_Score(self):
#         print(
#             f"{self.ID}Student {self.name}'s Examination is: Chinese:{self.Chinese} Math:{self.Math} English:{self.English}")
#
#
# Stu = Student('liuzhua', 20203985, 120, 100, 19)
# Stu.Score_Setting()
# Stu.Print_Score()


# class employee:
#     def __init__(self, name, id):
#         self.Employee_Name = name
#         self.Employee_ID = id
#
#     def print_info(self):
#         print(f"name:{self.Employee_Name} ID:{self.Employee_ID}")
#
#
# class FullTimeEmployee(employee):
#     def __init__(self, name, id):
#         super().__init__(name, id)
#         self.monthly_salary = 10000
#
#     def calculate_monthly_pay(self):
#         salary = self.monthly_salary
#         return salary
#
#
# class PartTimeEmployee(employee):
#     def __init__(self, name, id, days):
#         super().__init__(name, id)
#         self.daily_salary = 300
#         self.Days = days
#
#     def calculate_monthly_pay(self):
#         salary = self.daily_salary * self.Days
#         return salary
#
#
# Employee1 = FullTimeEmployee('zhangsan', '1006')
# Employee2 = PartTimeEmployee('lisi', '1009', 30)
# Employee1.print_info()
# print(f"FullTimeEmployee salary:{Employee1.calculate_monthly_pay()}")
# Employee2.print_info()
# print(f"PartTimeEmployee salary:{Employee2.calculate_monthly_pay()}")

# f = open("./data.txt", "r", encoding="utf-8")
# content = f.read()
# print(content)
# f.close()

# with open("./data.txt", "r", encoding="utf-8") as f:
#     # content = f.read()
#     # print(content)
#     # print(f.readline())
#     # print(f.readline())
#     lines = f.readlines()
#     for line in lines:
#         print(line)

# with open("./data.txt", "w", encoding="utf-8") as f:
#     f.write("我欲乘风归去，\n")
#     f.write("又恐琼楼玉宇，\n")
#     f.write("高处不胜寒。\n")
#     # content = f.read()
#     # print(content)
#
# with open("./data.txt", "a", encoding="utf-8") as f:
#     f.write("起舞弄清影，\n")
#     f.write("何似在人间。\n")
#
# with open("./data.txt", "r", encoding="utf-8") as f:
#     content = f.read()
#     print(content)























